//
//  CityInfoAreaListInfoView.m
//  CityInfoChooseView
//
//  Created by 正合适 on 2017/10/12.
//  Copyright © 2017年 正合适. All rights reserved.
//

#import "CityInfoAreaListInfoView.h"
#import "CityInfoTableView.h"

#define BASE_TAG 100
#define MAX_PAGES 3
#define INIT_CITY_ID @"100000"

@interface CityInfoAreaListInfoView ()<UIScrollViewDelegate>
/**主scrollview*/
@property (nonatomic, strong) UIScrollView *mainScrollView;
/**数据源*/
@property (nonatomic, strong) NSMutableArray *datas;
/**当前index*/
@property (nonatomic, assign) NSInteger currentIndex;
@end

@implementation CityInfoAreaListInfoView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self defaultData];
        [self createUI];
    }
    return self;
}

- (void)defaultData {
    _currentIndex = 0;
    _datas = [NSMutableArray array];
}

#pragma mark - 初始化界面
- (void)createUI {
    _mainScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _mainScrollView.pagingEnabled = YES;
    _mainScrollView.delegate = self;
    [self addSubview:_mainScrollView];
    _mainScrollView.contentSize = CGSizeMake(0, _mainScrollView.frame.size.height);
    NSArray *arr = [CityInfoModel loadCityInfoFromDatabaseId:INIT_CITY_ID];
    [_datas addObject:arr.mutableCopy];
    [self createTableViewWithTag:BASE_TAG+0];
}

#pragma mark - 创建tableview
- (void)createTableViewWithTag:(NSInteger)tag {
    __weak typeof(self) weakself = self;
    CityInfoTableView *tableView = [[CityInfoTableView alloc] initWithFrame:CGRectMake(_mainScrollView.frame.size.width*_currentIndex, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
    tableView.tag = tag;
    tableView.tableViewCellCilckBlock = ^(NSInteger section, NSInteger row) {
        BOOL isClose = NO;
        if (section-BASE_TAG == MAX_PAGES-1) {
            isClose = YES;
        }
        [weakself dealDataAndUIWithSection:section-BASE_TAG row:row isNeedCloseView:isClose];
    };
    [_mainScrollView addSubview:tableView];
    [tableView configData:_datas[_currentIndex]];
    _mainScrollView.contentSize = CGSizeMake(_mainScrollView.frame.size.width*(_currentIndex+1), _mainScrollView.frame.size.height);
}

#pragma mark - 刷新tableview
- (void)reloadTableDataWith:(NSInteger)tag data:(NSArray<CityInfoModel *> *)data {
    CityInfoTableView *tableView = (CityInfoTableView *)[self viewWithTag:tag];
    [tableView configData:data];
}

#pragma mark - 更新tableview
- (void)refreshDatasWithSection:(NSInteger)section row:(NSInteger)row {
    NSMutableArray *tempArr = [NSMutableArray array];
    for (NSInteger i = 0; i < [_datas[section] count]; i ++) {
        CityInfoModel *model = _datas[section][i];
        model.isSelected = row == i ? YES: NO;
        [tempArr addObject:model];
    }
    [_datas replaceObjectAtIndex:section withObject:tempArr];
}

#pragma mark - 管理选中的CityInfoModel
- (NSArray <CityInfoModel *>*)managerSelectedModelArr {
    NSMutableArray *selecteArr = [NSMutableArray array];
    for (NSArray *arr in _datas) {
        for (CityInfoModel *model in arr) {
            if (model.isSelected == YES) {
                [selecteArr addObject:model];
            }
        }
    }
    return selecteArr;
}

- (void)dealDataAndUIWithSection:(NSInteger)section row:(NSInteger)row isNeedCloseView:(BOOL)isNeedCloseView {
    // 刷新当前tableview，获取下一个tableview
    CityInfoModel *currentModel = _datas[section][row];
    NSArray *nextArr = [CityInfoModel loadCityInfoFromDatabaseId:currentModel.areaId];
    if (section <= (NSInteger)[_datas count]-2) {
        if (currentModel.isSelected) {
            // 选择的为同一个，直接滚动到下一页
            if (section < MAX_PAGES-1) {
                _currentIndex = section+1;
                [_mainScrollView setContentOffset:CGPointMake(_mainScrollView.frame.size.width*(_currentIndex), 0) animated:YES];
            }
            return;
        } else {
            // 重新刷新后面的数据
            NSMutableArray *arr = [NSMutableArray array];
            arr = _datas.mutableCopy;
            while ((NSInteger)[_datas count]-2 >= section) {
                CityInfoTableView *tableview = [_mainScrollView viewWithTag:(NSInteger)[_datas count]+BASE_TAG-1];
                [tableview removeFromSuperview];
                [_datas removeObjectAtIndex:(NSInteger)[_datas count]-1];
            }
        }
    }
    
    // 当前页面是否为最大级(下一页并不存在时)
    // _currentIndex 表示当前页面
    if (nextArr.count == 0 || (section == MAX_PAGES-1 && _datas.count == MAX_PAGES)) {
        // 最大级 不进入下一页
        _currentIndex = section;
    } else {
        // 非最大级
        _currentIndex = section+1;
        [_datas addObject:nextArr];
        if (_datas.count <= MAX_PAGES && section <=MAX_PAGES-2) {
            // 进入下一级
            [self createTableViewWithTag:_currentIndex+BASE_TAG];
        }
    }
    [self refreshDatasWithSection:section row:row];
    // 刷新tableview
    [self reloadTableDataWith:section+BASE_TAG data:_datas[section]];
    [self reloadTableDataWith:_currentIndex+BASE_TAG data:_datas[_currentIndex]];
    [_mainScrollView setContentOffset:CGPointMake(_mainScrollView.frame.size.width*(_currentIndex), 0) animated:YES];
    // 只有是在最后一页选择，调用回调block,关闭view
    if (_currentIndex == section) {
        [self scrollviewEndScroll:isNeedCloseView];
    }
}

#pragma mark - tableview点击的数据处理，ui交互
- (void)dealDataAndUIWithSection:(NSInteger)section row:(NSInteger)row {
    [self dealDataAndUIWithSection:section row:row isNeedCloseView:NO];
}

#pragma mark - UIScrollView滚动结束回调
- (void)scrollviewEndScroll:(BOOL)isClose {
    NSInteger index = ceilf(_mainScrollView.contentOffset.x/_mainScrollView.frame.size.width);
    if (self.listViewEndScrollBlock) {
        self.listViewEndScrollBlock(index,[self managerSelectedModelArr],isClose?1:0);
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollviewEndScroll:NO];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self scrollviewEndScroll:NO];
}

#pragma mark - ------- public -------

- (void)configScrollToPageWithIndex:(NSInteger)index {
    _currentIndex = index;
    [_mainScrollView setContentOffset:CGPointMake(_mainScrollView.frame.size.width*(_currentIndex), 0) animated:YES];
}

- (void)configAreas:(NSArray <NSDictionary *>*)areas {
    for (NSInteger i = 0; i < areas.count; i ++) {
        NSDictionary *area = areas[i];
        NSString *parentId = INIT_CITY_ID;
        if (i != 0) {
            NSDictionary *preArea = areas[i-1];
            parentId = preArea[@"areaId"];
        }
        NSArray *arr = [CityInfoModel loadCityInfoFromDatabaseId:parentId];
        NSInteger row = 0;
        for (NSInteger a = 0; a < arr.count; a ++) {
            CityInfoModel *model = arr[a];
            NSString *areaId = area[@"areaId"];
            if (model.areaId.integerValue == areaId.integerValue) {
                row = a;
            }
        }
        [self dealDataAndUIWithSection:i row:row];
    }
}


@end
